import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class TestJDBCSelect {
    public static void main(String[] args) throws SQLException {

        //创建数据源
        DataSource dataSource = new MysqlDataSource();

        ((MysqlDataSource)dataSource).setURL("jdbc:mysql://127.0.0.1:3306/schoolmessage?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("123456");

        //建立连接
        Connection connection = dataSource.getConnection();

        //操作数据库，拼接SQL
        String sql = "select * from student";
        PreparedStatement a = connection.prepareStatement(sql);

        //执行SQL
        //此时查询操作的返回值是 resultSet临时表
        ResultSet resultSet = a.executeQuery();

        //遍历resultSet，先获取临时表的每一行再获取每一行的若干列
        //next方法表示获取到一行记录，同时把光标往后移动一行，如果遍历结束next就直接返回false
        System.out.println("你的查询结果如下：");
        while (resultSet.next()){

            //针对当前这一行来获取它的列
            int id = resultSet.getInt("id");
            String name = resultSet.getString("name");
            String address = resultSet.getString("address");
            System.out.println("id =" + id + ", name =" + name + ", 地址: " + address);
        }

        //释放资源
        resultSet.close();
        a.close();
        connection.close();
    }
}
